# services/paypal.py
import os, requests

PAYPAL_ENV = os.getenv("PAYPAL_ENV", "sandbox")
BASE = "https://api-m.sandbox.paypal.com" if PAYPAL_ENV == "sandbox" else "https://api-m.paypal.com"
CLIENT_ID = os.getenv("PAYPAL_CLIENT_ID")
SECRET = os.getenv("PAYPAL_SECRET")

class PaypalError(Exception):
    pass

def _token():
    r = requests.post(
        f"{BASE}/v1/oauth2/token",
        auth=(CLIENT_ID, SECRET),
        data={"grant_type": "client_credentials"},
        timeout=15,
    )
    if r.status_code != 200:
        raise PaypalError(f"token error: {r.status_code} {r.text}")
    return r.json()["access_token"]

def create_order(amount_cents: int, currency: str, reference_id: str):
    """intent=CAPTURE，服务端权威金额"""
    access = _token()
    body = {
        "intent": "CAPTURE",
        "purchase_units": [{
            "reference_id": reference_id,
            "amount": {
                "currency_code": currency,
                "value": f"{amount_cents/100:.2f}"
            }
        }]
    }
    r = requests.post(
        f"{BASE}/v2/checkout/orders",
        headers={"Authorization": f"Bearer {access}", "Content-Type": "application/json"},
        json=body, timeout=20
    )
    if r.status_code not in (201, 200):
        raise PaypalError(f"create order err: {r.status_code} {r.text}")
    j = r.json()
    return j["id"]  # orderID

def capture_order(order_id: str):
    access = _token()
    r = requests.post(
        f"{BASE}/v2/checkout/orders/{order_id}/capture",
        headers={"Authorization": f"Bearer {access}", "Content-Type": "application/json"},
        timeout=20
    )
    if r.status_code not in (201, 200):
        raise PaypalError(f"capture err: {r.status_code} {r.text}")
    return r.json()
